package no.knowit.eventorama.util;

import java.util.logging.Logger;

import com.google.appengine.api.xmpp.JID;
import com.google.appengine.api.xmpp.Message;
import com.google.appengine.api.xmpp.MessageBuilder;
import com.google.appengine.api.xmpp.SendResponse;
import com.google.appengine.api.xmpp.XMPPService;
import com.google.appengine.api.xmpp.XMPPServiceFactory;

/**
 * 
 * Helper class for XMPP
 *
 */
public class XMPPUtil {

	private static final Logger log = Logger
			.getLogger(XMPPUtil.class.getName());

	/**
	 * Sends a message to a user using the XMPP protocol
	 * 
	 * 
	 * @param receiverJID receiver of the message (usually the email of the user)
	 * @param msgBody body of the message
	 * @return true if message was sent
	 */
	public static boolean sendMessage(JID receiverJID, String msgBody) {
		Message msg = new MessageBuilder().withRecipientJids(receiverJID)
				.withBody(msgBody).build();

		boolean messageSent = false;
		XMPPService xmpp = XMPPServiceFactory.getXMPPService();
		boolean receiverIsAvailable = xmpp.getPresence(receiverJID)
				.isAvailable();
		
		if (receiverIsAvailable) {
			SendResponse status = xmpp.sendMessage(msg);
			messageSent = (status.getStatusMap().get(receiverJID) == SendResponse.Status.SUCCESS);

			String msgInfo = "SendResponse=" + status + "receiverJID="
					+ receiverJID + ", receiverIsAvailable= "
					+ receiverIsAvailable;

			if (!messageSent) {
				String errorMsg = "Unable to send XMPP message. " + msgInfo;
				log.warning(errorMsg);
			}

		}
		
		return messageSent;
	}

}
